var app = getApp();
var ux = require('../../../lib/ux.js');
var QQMapWX = require('../../../utils/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    qrCodeUrl: "/api/memberCoupon/smallProgramCode.do",
    authDZs:false,
    isShow:true,
    animationAddressMenu: {},
    addressMenuIsShow: false, 
    list: [],
    agentType:0,
    area: {},
    country: {},
    userInfo: {},
    thisType: 0,
    thisSelectId:null,
    pidUrl: "/api/address/pidAdderssList.do",
    editUrl: "/api/memberUser/editMeberPlace.do",
    merchant:null,
    action: "/api/memberUser/getUserInfoData.do",
    submit: "{{submit}}"
  },
  downLoadImg: function (netUrl, storageKeyUrl) {
    wx.getImageInfo({
      src: netUrl,    //请求的网络图片路径
      success: function (res) {
        //请求成功后将会生成一个本地路径即res.path,然后将该路径缓存到storageKeyUrl关键字中
        // wx.setStorageSync("token", data.data.token);
        wx.setStorage({
          key: storageKeyUrl,
          data: res.path,
        });

      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var self=this;
    ux.login(function (protocol) {
      if (protocol.success) {
        wx.setStorageSync("userInfo", protocol.data.userInfo);
        wx.setStorageSync("token", protocol.data.token);
        self.setData({
          userInfo: protocol.data.userInfo
        })
        var userInfo = wx.getStorageSync("userInfo");
        if (userInfo.authStatus == 0) {
          self.setData({
            authDZs: true
          })
        }
          if(self.data.isShow){
            self.setData({
              isShow:false,
              list: [],
              agentType: 0,
              area: {},
              country: {},
              userInfo: {},
              thisType: 0,
            })
            var options={};
            options.banrdId = self.data.merchant;
            wx.showLoading({
              title: '加载中...',
            })
            ux.request(self.data.action, options, function (data) {
              self.setData({
                dzf: data.data.dzf,
                dfh: data.data.dfh,
                dsh: data.data.dsh,
                sh: data.data.sh,
                agentType: data.data.agentType,
                userInfo: data.data.userInfo,
                count: data.data.count,
                money: data.data.money
              })
              var ppaa = { banrdId: self.data.merchant }
              ux.request(self.data.qrCodeUrl, ppaa, function (protocol) {
                wx.hideLoading();
                if (protocol.data.qrcode) {
                  self.setData({
                    qrcode: protocol.data.qrcode
                  })
                  self.downLoadImg(protocol.data.hb, 'hb');
                  self.downLoadImg(protocol.data.qrcode, 'qrcode');
                }
              }, true);
              wx.hideLoading();
            }, true);
          }
      }
    });
  },
  toZhuanQu:function(){
    wx.navigateTo({
      url: '/pages/member/tab1/agent/hhrCard?long=' + wx.getStorageSync("longitude") + '&lan=' + wx.getStorageSync("latitude") + '&banrdId=' + wx.getStorageSync("banrdId"),
    })
  },
  toLibao:function(){
    wx.navigateTo({
      url: '/pages/member/tab1/agent/cardPay?banrdId=' + wx.getStorageSync("banrdId"),
    })
  },
  /**
  * 生命周期函数--监听页面隐藏
  */
  onHide: function () {
   this.setData({
     isShow:true
   })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {//还没取数据
  var self=this;
    this.setData({
      merchant: wx.getStorageSync("banrdId")
    });
    qqmapsdk = new QQMapWX({
      key: 'B5WBZ-NBAHJ-MJQFY-F4RWO-MPNOV-NNBQC' //这里自己的key秘钥进行填充
    });
    // 初始化动画变量
    var animation = wx.createAnimation({
      duration: 800,
      transformOrigin: "50% 50%",
      timingFunction: 'ease',
    })
    this.animation = animation;
  },
  getUserInfoFun: function (e) {
    console.log("dddddddddddddd");
    var self = this;
    var userInfo = e.detail.userInfo
    var params = {};
    params.nickname = userInfo.nickName;
    params.header = userInfo.avatarUrl;
    params.sex = userInfo.gender;
    console.log(JSON.stringify(userInfo));
    wx.showLoading({
      mask: true,
      title: '处理中....',
    })
    wx.login({
      success: function (res) {
        if (res.code) {
          params.jscode = res.code;
          ux.request("/api/member/registerUser.do", params,
            function (protocol) {
              if (protocol.success) {
                wx.setStorageSync("userInfo", protocol.data.userInfo);
                wx.setStorageSync("token", protocol.data.token);
                wx.setStorageSync("pingtai", protocol.data.pingtai);
                wx.hideLoading();
                self.setData({
                  userInfo: protocol.data.userInfo,
                  authDZs: false
                })
              } else {
                wx.hideLoading();
                wx.showToast({
                  title: '系统繁忙!',
                })
              }
            }, true);
        } else {
          wx.hideLoading();
          console.log('登录失败！' + res.errMsg)
        }
      },
      complete: function (res) {
        console.log(JSON.stringify(res))
      }
    })
  },
  onForm: function (event) {
    if (this.data.submit) {
      var $this = this;
      var dataset = event.currentTarget.dataset;
      ux.request(this.data.submit, detail.value, function (protocol) {
        if (protocol.success) {
          if (dataset.url) {
            wx.redirectTo(dataset.url);
          }
        }
      }, true);
    }
  },

  onTap: function (event) {
    var dataset = event.currentTarget.dataset;
    var data = this.data;
    if (dataset.key && dataset.val) {
      data[dataset.key] = dataset.val;
    }
    this.setData(data);
  },
  toAgent: function () {
    var pa = { long: wx.getStorageSync("longitude"), lan: wx.getStorageSync("latitude") }
    wx.navigateTo({
      url: '/pages/member/tab1/agent/applyAgent?pa=' + JSON.stringify(pa),
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


 

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
 
  toMyDistribution:function(){
    wx.navigateTo({
      url: '/pages/member/tab3/distribution/MyDistribution',
    })
  },
  toast: function (params) {
    if (typeof (params) == "string") {
      params = { content: params };
    }
    this.setData({
      toast: params.content
    });
    var THIS = this;
    setTimeout(function () {
      THIS.setData({
        toast: false
      });
      if (params.complete) {
        params.complete();
      }
    }, params.time || 3000);
  },



  // 点击所在地区弹出选择框
  selectDistrict: function (e) {
    var that = this
    // 如果已经显示，不在执行显示动画
    if (that.data.addressMenuIsShow) {
      return
    }
    // 执行显示动画
    that.startAddressAnimation(true)
  },
  // 执行动画
  startAddressAnimation: function (isShow) {
    var that = this
    if (isShow) {
      // vh是用来表示尺寸的单位，高度全屏是100vh
      that.animation.translateY(0 + 'vh').step()
    } else {
      that.animation.translateY(100 + 'vh').step()
    }
    that.setData({
      animationAddressMenu: that.animation.export(),
      addressMenuIsShow: isShow,
    })
  },
  getProvince: function () {
    var $this = this;
    var params = { pid: 0 }
    ux.request(this.data.pidUrl, params, function (protocol) {
      $this.setData({
        list: protocol.data.list,
        thisType: 1,
        province: {},
        city: {},
        area: {},
        country: {}
      });
    }, true);
  },
  getCity: function () {
    var $this = this;
    var params = { pid: this.data.province.id }
    ux.request(this.data.pidUrl, params, function (protocol) {
      $this.setData({
        list: protocol.data.list,
        thisType: 2,
        city: {},
        area: {},
        country: {}
      });
    }, true);
  },
  getArea: function () {
    var $this = this;
    var params = { pid: this.data.city.id }
    ux.request(this.data.pidUrl, params, function (protocol) {
      $this.setData({
        list: protocol.data.list,
        thisType: 3,
        area: {},
        country: {}
      });
    }, true);
  },
  getCountry: function () {
    var $this = this;
    var params = { pid: this.data.area.id }
    ux.request(this.data.pidUrl, params, function (protocol) {
      $this.setData({
        list: protocol.data.list,
        thisType: 4,
        country: {}
      });
    }, true);
  },
  selectThis: function (event) {
    var dataset = event.currentTarget.dataset;
    var lists = this.data.list;
    var index = dataset.index;
    if (this.data.thisType == 1) {
      this.setData({
        province: lists[index],
        thisSelectId: lists[index].id,
        thisColor: 1
      })
      this.getCity();
    } else if (this.data.thisType == 2) {
      this.setData({
        city: lists[index],
        thisSelectId: lists[index].id,
        thisColor: 2
      })
      this.getArea();
    } else if (this.data.thisType == 3) {
      this.setData({
        area: lists[index],
        thisSelectId: lists[index].id,
        thisColor: 3
      })
      this.getCountry();
    } else if (this.data.thisType == 4) {
      this.setData({
        country: lists[index],
        thisSelectId: lists[index].id,
        thisColor: 4
      })
    }

  },
  citySure: function () {
    var self=this;
    if (!self.data.area.id) {
      wx.showToast({
        title: '选择区/县',
      })
      return false;
    }
    var params = { adressId:self.data.thisSelectId}
    ux.request(this.data.editUrl, params, function (protocol) {
      self.setData({
        userInfo:protocol.data.userInfo
      });
      self.startAddressAnimation(false)
    }, true);
  },
  cityCancel:function(){
    this.startAddressAnimation(false)
  },
  toDistributor: function () {
    if (wx.getStorageSync("distributor")){
      wx.reLaunch({
        url: '/pages/distributor/tab1/myOrder',
      })
    }else{
      wx.navigateTo({
        url: '/pages/distributor/loginPage',
      })
    }
  },
  toLX:function(){
      var pa = {};
      pa.province = wx.getStorageSync("province");
      pa.city = wx.getStorageSync("city");
      pa.country = wx.getStorageSync("district");
      pa.long = wx.getStorageSync("longitude");
      pa.lan = wx.getStorageSync("latitude");
      wx.navigateTo({
        url: '/pages/member/tab3/other/ContactBrand?pa=' + JSON.stringify(pa),
      })
  },
  toCards: function () {
      var pa = { long: wx.getStorageSync("longitude"), lan: wx.getStorageSync("latitude") }
      wx.navigateTo({
        url: '/pages/member/tab1/agent/applyAgent?pa=' + JSON.stringify(pa),
      })
  },
})
